﻿using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views.Animations;
using Android.Widget;
using AndroidX.AppCompat.App;
using AndroidX.CardView.Widget;
using BlackBoxForU.Feature;
using System;

namespace BlackBoxForU
{
    [Activity(Label = "盲盒抽奖", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);
            Feature.SettingUtil.Init(this);
            TextView view = (TextView)FindViewById(Resource.Id.checksign);
            view.Text = SettingUtil.Sign;
            Limited.CheckForLimit(this);
            TextView idcode = (TextView)FindViewById(Resource.Id.idcode);
            idcode.Text = $"您的身份验证码：{Limited.InitCode.ToUpper()}\n于{Limited.InitDate.Year}年{Limited.InitDate.Month}月{Limited.InitDate.Day}日 {Limited.InitDate.Hour.ToString().PadLeft(2, '0')}:{Limited.InitDate.Minute.ToString().PadLeft(2, '0')} 创建";
            idcode.LongClick += Idcode_LongClick;
            TextView go = (TextView)FindViewById(Resource.Id.go);
            go.LongClick += Go_LongClick;
            go.Click += Go_Click;
            TextView r = (TextView)FindViewById(Resource.Id.result);
            r.Click += R_Click;
            r.Text = $"当前配置：\n{LuckDraw.SettingText}";
        }

        private void Idcode_LongClick(object sender, Android.Views.View.LongClickEventArgs e)
        {
            PasteBoard.setClipBoardText(this, Limited.InitCode);
        }

        private void Go_LongClick(object sender, Android.Views.View.LongClickEventArgs e)
        {
            EditText inputServer = new EditText(this);
            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
            builder.SetTitle("请输入您的兑换码").SetView(inputServer);
            builder.SetNegativeButton("取消", delegate (Object obj, DialogClickEventArgs arg)
            {
            }
);
            builder.SetPositiveButton("确定", delegate (Object obj, DialogClickEventArgs arg)
            {
                try
                {
                    ///"loveU,{number}"
                    string code = inputServer.Text;
                    string oldinitcode = Limited.InitCode;
                    DataProcess.Encryption.Encryption encryption = new DataProcess.Encryption.Encryption();
                    string[] codearr = code.Split('|');
                    code = codearr[0];
                    string text = encryption.AdvancedDecrypt(code, oldinitcode, System.Text.Encoding.UTF8);
                    string[] arr = text.Split(',');
                    if (arr.Length == 6)
                    {
                        arr[0] = "LoveU";
                        int app = 0, y, m, d;
                        long createtime = 0;
                        int.TryParse(arr[1], out app);
                        int.TryParse(arr[2], out y);
                        int.TryParse(arr[3], out m);
                        int.TryParse(arr[4], out d);
                        long.TryParse(arr[5], out createtime);
                        DateTime date = new DateTime(y, m, d);
                        if (date >= DateTime.Now.Date && long.Parse(codearr[1]) == createtime)
                        {
                            Limited.MoreTimeChange(this, app);
                            if (app > 0)
                            {
                                Limited.ReSetInitCode(this, createtime);
                                TextView idcode = (TextView)FindViewById(Resource.Id.idcode);
                                idcode.Text = $"您的身份验证码：{Limited.InitCode.ToUpper()}\n于{Limited.InitDate.Year}年{Limited.InitDate.Month}月{Limited.InitDate.Day}日 {Limited.InitDate.Hour.ToString().PadLeft(2, '0')}:{Limited.InitDate.Minute.ToString().PadLeft(2, '0')} 创建";
                                Toast.MakeText(this, $"成功兑换{app}次抽奖机会", ToastLength.Short).Show();
                            }
                        }
                        else
                        {
                            Toast.MakeText(this, $"兑换失败", ToastLength.Short).Show();
                        }


                    }
                    else
                        Toast.MakeText(this, $"兑换失败", ToastLength.Short).Show();
                }
                catch
                {
                    Toast.MakeText(this, $"兑换失败", ToastLength.Short).Show();
                }

            }
            );
            builder.Show();
        }

        private void R_Click(object sender, EventArgs e)
        {
            object text = ((TextView)sender).Tag;
            if (text != null)
            {
                PasteBoard.setClipBoardText(this, text.ToString());
            }
        }
        void main()
        {
            Animation scale = AnimationUtils.LoadAnimation(this, Resource.Animation.scale);
            ((CardView)FindViewById(Resource.Id.card_go)).StartAnimation(scale);


            DateTime d = DateTime.Now;
            string result = LuckDraw.Start();
            TextView r = (TextView)FindViewById(Resource.Id.result);
            r.Text = "很遗憾，并未中奖";
            if (!result.Equals("未中奖"))
            {
                if (result.Equals("再来一次"))
                {
                    r.Text = "恭喜你，获得多抽一次的机会！";
                    Limited.MoreTimeChange(this, 1);
                }
                else
                {
                    r.Text = $"于{d.Year}年{d.Month}月{d.Day}日 {d.Hour.ToString().PadLeft(2, '0')}:{d.Minute.ToString().PadLeft(2, '0')}\n 获得 -{result}-";
                    DataProcess.Encryption.Encryption encryption = new DataProcess.Encryption.Encryption();
                    string sign = encryption.AdvancedEncrypt($"中奖了!在{d.ToString()}时抽奖并中了{result}！", Limited.InitCode, System.Text.Encoding.UTF8);
                    r.Text += "\n中奖验证码如下：\n" + sign + "\n请及时发给兑奖人进行兑奖!";
                    r.Tag = sign;
                    PasteBoard.setClipBoardText(this, sign);
                }
            }
            Limited.UseForRight(this);
        }

        private void Go_Click(object sender, System.EventArgs e)
        {
            if (Limited.CheckForRights(this))
            {
                main();
            }
            else
            {
                int moretime = Limited.getMoreTime(this);
                if (moretime > 0)
                {
                    Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(this);
                    builder.SetTitle("请选择");
                    builder.SetMessage($"是否要使用多余的次数?(剩余:{moretime})");
                    builder.SetNegativeButton("否，我不想", delegate (Object obj, DialogClickEventArgs arg)
                     {
                     }
                    );
                    builder.SetPositiveButton("是,再抽一次！", delegate (Object obj, DialogClickEventArgs arg)
                    {
                        Limited.MoreTimeChange(this, -1);
                        main();
                    }
                    );
                    builder.Create().Show();
                }
                else
                    Toast.MakeText(this, "今日已抽过，请明天再来吧！", ToastLength.Short).Show();
            }
        }

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}